package com.cms.recursoshumanos.handler;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import net.rim.device.api.xml.parsers.SAXParser;
import net.rim.device.api.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;

import com.cms.recursoshumanos.transport.BBRequest;
import com.cms.recursoshumanos.transport.HttpRequest;
import com.cms.recursoshumanos.xml.handler.XMLObjectHandler;

public class JParserHandler 
{
	
	private static JParserHandler instance = null;

	public static JParserHandler getInstance()
	{
		if (instance == null)
		{
			instance = new JParserHandler();
		}
		return instance;
	}
	public JParserHandler() 
	{
		
	}
	
	public String procesarXML(BBRequest request) 
	{
		HttpRequest httpRequest = (HttpRequest) request;
        byte[] dataBytes = httpRequest.getResponseByte();

        ByteArrayInputStream bis = new ByteArrayInputStream(dataBytes);
        
        byte[] buffer = new byte[1024];
        StringBuffer sb = new StringBuffer();
        int readIn = 0;
        
        try 
        {
			while((readIn = bis.read(buffer)) > 0)
			{
				String temp = new String (buffer, 0, readIn);
				sb.append(temp);
			}
		} 
        catch (IOException e) 
        {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        return parseXML(sb);
        
	}
	public String parseXML(StringBuffer sb)
	{
		String xml = sb.toString();
		String arreglo_ayuda = xml.substring(3,xml.length()-1);
        ByteArrayInputStream bais = new ByteArrayInputStream(arreglo_ayuda.getBytes());       
        return getXMLObjects(bais);
	}
	public static String getXMLObjects(InputStream is) 
	{
        XMLObjectHandler xmlObjectHandler = new XMLObjectHandler();
        try 
        {
        	SAXParserFactory factory = SAXParserFactory.newInstance();	
  	      	SAXParser saxParser = factory.newSAXParser();
  	      	saxParser.parse(is, xmlObjectHandler);
        } 
        catch (net.rim.device.api.xml.parsers.ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        catch (SAXException e) 
        {
        	e.printStackTrace();
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
        return xmlObjectHandler.getXMLResult();
    }
	
}
